package com.atguigu.mySmartCampus.util;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper{
    //expiration 过期
    private static long tokenExpiration = Long.valueOf(24*60*60*1000);
    private static String tokenSignKey ="123456";

//Signature  签名
//Algorithm  算法
//compact   紧密
    public static String createToken(Long userId,Integer userType){
        JwtBuilder builder = Jwts
                .builder()
                .setSubject("YYGH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId",userId)
                .claim("userType",userType)
                .signWith(SignatureAlgorithm.HS512,tokenSignKey)
                .compressWith(CompressionCodecs.GZIP);
        String token = builder.compact();

        return token;
    }


    public static Claims getClaimsJws(String token){
        if(StringUtils.isEmpty(token)) return null;
        JwtParser parse = Jwts.parser();
        JwtParser jwtParser = parse.setSigningKey(tokenSignKey);
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }

    public static Long getUserId(String token){        
         
        Claims cliams = getClaimsJws(token);
        Integer userId = (Integer)cliams.get("userId");
        return userId.longValue();
    }


    public static Integer getUserType(String token){
        Claims cliams = getClaimsJws(token);
        return (Integer) cliams.get("userType");
    }


    public static String getUserName(String token){
        Claims cliams = getClaimsJws(token);
        return (String) cliams.get("userName");
    }


    public static boolean isExpiration(String token){
        try{
            //没有过期，有效，返回是false
            Date expiration = getClaimsJws(token).getExpiration();
            boolean before = expiration.before(new Date());
            return before;
        }catch(Exception e){
            return true;
        }
    }
}
